package com.zb.smbmsc.servlet.user;

import com.zb.smbmsc.pojo.User;
import com.zb.smbmsc.service.user.UserService;
import com.zb.smbmsc.service.user.UserServiceImpl;
import com.zb.smbmsc.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    UserService userService = null;

    public LoginServlet(){
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        User user = userService.login(userCode, userPassword);
        if(null != user){
            if (user.getUserPassword().equals(userPassword)){
                req.getSession().setAttribute(Constants.USER_SESSION, user);
                resp.sendRedirect(req.getContextPath() + "/jsp/frame.jsp");
            }else{
                req.setAttribute("error", "用户名或密码错误！");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }else{
            req.setAttribute("error", "用户名或密码错误！");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
